<template>
    <div class="progress-container">
        <div class="progress-bar" :style="{ width: progressBarWidth }"></div>
        <div class="progress-text">{{ scrolledPercentage.toFixed(2) }}%</div>
        <div @click="scrollToTop">
            <img-icon name="top" size="1rem" class="mr isClick" />
        </div>
        <div @click="scrollToBottom">
            <img-icon name="bottom" size="1rem" class="mr isClick" />
        </div>
    </div>
</template>

<script>
import ImgIcon from "./ImgIcon.vue";

export default {
    components: { ImgIcon },
    data() {
        return {
            progressBarWidth: "0%", // 初始进度条宽度为0%
            scrolledPercentage: 0, // 初始滚动百分比为0
        };
    },
    mounted() {
        window.addEventListener("scroll", this.updateProgressBar); // 监听滚动事件
    },
    destroyed() {
        window.removeEventListener("scroll", this.updateProgressBar); // 移除滚动事件监听
    },
    methods: {
        updateProgressBar() {
            const scrollHeight = document.documentElement.scrollHeight; // 整个页面的高度
            const scrollTop = window.scrollY || window.pageYOffset; // 当前滚动位置
            const windowHeight = window.innerHeight; // 可视窗口的高度

            this.scrolledPercentage =
                (scrollTop / (scrollHeight - windowHeight)) * 100; // 计算滚动百分比
            this.progressBarWidth = `${this.scrolledPercentage}%`; // 更新进度条宽度
        },
        scrollToTop() {
            window.scrollTo({ top: 0, behavior: "smooth" }); // 平滑滚动到页面顶部
        },
        scrollToBottom() {
            const scrollHeight = document.documentElement.scrollHeight; // 整个页面的高度
            window.scrollTo({ top: scrollHeight, behavior: "smooth" }); // 平滑滚动到页面底部
        },
    },
};
</script>

<style lang="scss" scoped>
@use "../assets/css/progress-bar.scss";
</style>
